package com.csii.security.controller;

import com.csii.core.api.Result;
import com.csii.security.properites.SecurityConstants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.Principal;

/**
 * @Auther: ian
 */
@Controller
public class CustomLoginController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${server.baseUrl}")
    private String baseUrl;
    @Value("${cola.security.loginPage}")
    private String loginPage;
    /**
     * 前往认证(登录)页面
     * @return
     */
    @GetMapping("/login/page")
    public ModelAndView toLogin(ModelAndView modelAndView) {
        modelAndView.addObject("baseUrl",baseUrl);
        //modelAndView.addObject("baseUrl","http://passport.sit.cqrcb.com/cas");
//        logger.info(baseUrl);
//        logger.info(loginPage);

        modelAndView.setViewName(loginPage);
        //modelAndView.setViewName("login");
        return modelAndView; // classpath: /templates/login.html
    }



    @Autowired
    private DefaultKaptcha defaultKaptcha;
    /**
     * 获取图形验证码
     */
    @GetMapping("/code/image")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应头image/jpeg
        response.setHeader("Content-Type","image/jpeg");
        // 1. 获取验证码字符串
        String code = defaultKaptcha.createText();
        logger.info("生成的图形验证码是：" + code);
        // 2. 字符串把它放到session中
        request.getSession().setAttribute(SecurityConstants.SESSION_KEY , code);
        // 3. 获取验证码图片
        BufferedImage image = defaultKaptcha.createImage(code);
        // 4. 将验证码图片把它写出去
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    @GetMapping("/sys/userInfo")
    @ResponseBody
    public Result userInfo(Principal principal) throws IOException {
        return  Result.ok(((AbstractAuthenticationToken)principal).getPrincipal());
    }
}
